package com.networkviwer.utils;

import java.sql.*;
import java.util.Map;

/**
 * @version V1.0
 * @Title:
 * @Package
 * @Description:
 * @author: runoob
 * @date:
 */
public class TasklistDatasourceUtil {

    static public Connection getConnection() throws ClassNotFoundException, SQLException {
        String url = "jdbc:h2:./database;MV_STORE=FALSE;MVCC=FALSE;TRACE_LEVEL_FILE=0;TRACE_LEVEL_SYSTEM_OUT=0";
        String driverClass = "org.h2.Driver";
        Class.forName(driverClass);
        return DriverManager.getConnection(url);
    }

    static public void createTable(Statement statement) throws SQLException {
        statement.execute("DROP TABLE IF EXISTS tasklist");
        statement.execute("create table tasklist(" +
                "id int(11) primary key auto_increment," +
                "image varchar(500)," +
                "pid int(11)," +
                "session varchar(32)," +
                "session_num varchar(20)," +
                "memory_usage varchar(20))"
        );
    }

    static public void insert(Statement statement, Map<String,String> valueMap) throws SQLException {
        // 添加数据
        statement.executeUpdate("insert into tasklist(image,pid,session,session_num,memory_usage) values(" +
                "'" + valueMap.get("image") + "'," +
                "" + valueMap.get("pid") + "," +
                "'" + valueMap.get("session") + "'," +
                "'" + valueMap.get("session_num") + "'," +
                "'" + valueMap.get("memory_usage") + "')");
    }

    static public ResultSet getAllData(Statement statement) throws SQLException {
        return statement.executeQuery("select * from tasklist");
    }

    static public void deleteAllData(Statement statement) throws SQLException {
        statement.executeUpdate("delete from tasklist");
    }

    static public ResultSet getData(Statement statement, Map<String,String> valueMap) throws SQLException {
        String sql = "select * from tasklist where 1=1 ";
        if (valueMap.containsKey("image")){
            sql += "and image like '%" + valueMap.get("image") + "%'";
        }
        if (valueMap.containsKey("pid")){
            sql += "and pid like '%" + valueMap.get("pid") + "%'";
        }
        if (valueMap.containsKey("session")){
            sql += "and session like '%" + valueMap.get("session") + "%'";
        }
        if (valueMap.containsKey("session_num")){
            sql += "and session_num like '%" + valueMap.get("session_num") + "%'";
        }
        if (valueMap.containsKey("memory_usage")){
            sql += "and memory_usage like '%" + valueMap.get("memory_usage") + "%'";
        }
        return statement.executeQuery(sql);
    }

}
